package com.bed.lovewithpatientbed.common.realm;

import com.bed.lovewithpatientbed.common.LoginSubjectType;
import com.bed.lovewithpatientbed.pojo.User;
import com.bed.lovewithpatientbed.service.IUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;

/**
 * @author xuxiaoding
 * @version 1.0.0
 * @ClassName OrdinaryUserRealm.java
 * @Description 普通用户认证授权Realm
 */
public class OrdinaryUserRealm extends AuthorizingRealm {

    private final LoginSubjectType loginSubjectType = LoginSubjectType.ORDINARY_USER;

    private IUserService userService;

    public LoginSubjectType getLoginSubjectType() {
        return loginSubjectType;
    }

    @Autowired
    public void setUserService(IUserService userService) {
        this.userService = userService;
    }

    /**
     * 普通用户登录认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        if (token == null) {
            return null;
        }
        // 获取需要认证的主体
        String username = (String) token.getPrincipal();
        if (username == null || "".equals(username)) {
            return null;
        }

        // 从user表中查询
        User user = userService.retrieveByUserPhone(username);
        if (ObjectUtils.isEmpty(user)) {
            return null;
        }

        return new SimpleAuthenticationInfo(user, user.getUserPassword(), this.getName());
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }
}
